package com.tengju.support.application.rule;

import com.tengju.support.application.shared.ApplicationException;
import com.tengju.support.application.shared.ApplicationExceptionCode;
import com.tengju.support.domain.model.rule.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class RuleService {

    @Autowired
    RuleRepository ruleRepository;


    public void registerRule(FullMatchRuleForm form,String operator) {
        Rule rule = RuleFactory.createFullMatchRule(form,operator);
        ruleRepository.store(rule);
    }

    public void editRule(FullMatchRuleForm form,String operator,RuleId ruleId) {

        if (ruleId == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_ID_EMPTY);
        }
        Rule rule = ruleRepository.queryRule(ruleId);
        if (rule == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_NOT_EXIST,ruleId.getValue());
        }
        Rule newRule = RuleFactory.createFullMatchRule(form,operator);
        rule.editRule(newRule);



    }


    public Rule getRule(RuleId ruleId) {
        if (ruleId == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_ID_EMPTY);
        }
        return ruleRepository.queryRule(ruleId);
    }


    public boolean evaluate(MetaInfo metaInfo,RuleId ruleId) {
        if (ruleId == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_ID_EMPTY);
        }
        Rule rule = ruleRepository.queryRule(ruleId);
        if (rule == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_NOT_EXIST,ruleId.getValue());
        }
        return rule.evaluate(metaInfo);
    }


    public List<Object> execute(MetaInfo metaInfo, RuleId ruleId) {
        if (ruleId == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_ID_EMPTY);
        }
        Rule rule = ruleRepository.queryRule(ruleId);
        if (rule == null) {
            throw ApplicationException.error(ApplicationExceptionCode.RULE_NOT_EXIST,ruleId.getValue());
        }
        return rule.execute(metaInfo);
    }






}
